package com.cheems.cheems_spring_ai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheems.cheems_spring_ai.domain.AiOperation;
import com.cheems.cheems_spring_ai.domain.vo.ConversationHistoryVO;
import com.cheems.cheems_spring_ai.domain.vo.ConversationVO;
import com.cheems.cheems_spring_ai.exception.BusinessException;
import com.cheems.cheems_spring_ai.common.ErrorCode;
import com.cheems.cheems_spring_ai.mapper.AiOperationMapper;
import com.cheems.cheems_spring_ai.service.AiOperationService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
* @author lenovo
* @description 针对表【ai_operation(调用ai记录表)】的数据库操作Service实现
* @createDate 2025-03-22 18:41:36
*/
@Service
public class AiOperationServiceImpl extends ServiceImpl<AiOperationMapper, AiOperation>
    implements AiOperationService {

    @Override
    public List<AiOperation> getHistoryByConversationId(String conversationId) {
        LambdaQueryWrapper<AiOperation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AiOperation::getConversationId, conversationId)
                .orderBy(true, true, AiOperation::getCreateTime);
        return this.list(queryWrapper);
    }
    
    @Override
    public List<ConversationHistoryVO> getConversationHistoryById(String conversationId, String henauNumber) {
        // 先验证该会话是否属于该用户
        LambdaQueryWrapper<AiOperation> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(AiOperation::getConversationId, conversationId)
                .eq(AiOperation::getHenauNumber, henauNumber)
                .last("LIMIT 1");
        
        AiOperation operation = this.getOne(checkWrapper);
        if (operation == null) {
            // 如果没有找到记录，说明该会话不属于该用户或不存在
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "该会话不存在或无权访问");
        }
        
        // 查询该会话的所有记录
        LambdaQueryWrapper<AiOperation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AiOperation::getConversationId, conversationId)
                .orderBy(true, true, AiOperation::getCreateTime);
        
        List<AiOperation> operations = this.list(queryWrapper);
        
        // 转换为VO对象
        return operations.stream().map(op -> {
            ConversationHistoryVO vo = new ConversationHistoryVO();
            BeanUtils.copyProperties(op, vo);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<String> getUserConversationIds(String henauNumber) {
        LambdaQueryWrapper<AiOperation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AiOperation::getHenauNumber, henauNumber)
                .select(AiOperation::getConversationId)
                .groupBy(AiOperation::getConversationId);
        
        List<AiOperation> operations = this.list(queryWrapper);
        return operations.stream()
                .map(AiOperation::getConversationId)
                .distinct()
                .collect(Collectors.toList());
    }

    @Override
    public String createNewConversation() {
        // 使用UUID生成唯一会话ID
        return UUID.randomUUID().toString();
    }
    
    @Override
    public List<ConversationVO> getUserConversations(String henauNumber) {
        // 先获取用户的所有会话ID
        List<String> conversationIds = getUserConversationIds(henauNumber);
        
        // 创建结果列表
        List<ConversationVO> result = new ArrayList<>();
        
        // 遍历每个会话ID，查找最后一条消息
        for (String conversationId : conversationIds) {
            // 查询该会话下的所有记录，按创建时间倒序排列
            LambdaQueryWrapper<AiOperation> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AiOperation::getConversationId, conversationId)
                    .eq(AiOperation::getHenauNumber, henauNumber)
                    .orderByDesc(AiOperation::getCreateTime);
            
            // 获取最后一条记录
            List<AiOperation> operations = this.list(queryWrapper);
            if (!operations.isEmpty()) {
                AiOperation lastOperation = operations.get(0);
                
                // 创建VO对象
                ConversationVO vo = new ConversationVO();
                vo.setConversationId(conversationId);
                vo.setLastUserInput(lastOperation.getUserInput());
                vo.setLastAiOutput(lastOperation.getAiOutput());
                vo.setLastMessageTime(lastOperation.getCreateTime());
                
                result.add(vo);
            }
        }
        
        // 按最后消息时间倒序排序
        result.sort(Comparator.comparing(ConversationVO::getLastMessageTime).reversed());
        
        // 只返回最近的5条记录（如果总数小于7，则返回全部）
        return result.size() <= 7 ? result : result.subList(0, 7);
    }
}




